package com.xiaoyg.gulimall.product.service.impl;

import com.xiaoyg.gulimall.product.dao.CategoryDao;
import com.xiaoyg.gulimall.product.entity.CategoryEntity;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyg.common.utils.PageUtils;
import com.xiaoyg.common.utils.Query;

import com.xiaoyg.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> all = baseMapper.selectList(new QueryWrapper<>(null));
        return getChildren(0L, all);
    }

    /**
     * 获取子菜单
     *
     * @param parentId
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(Long parentId, List<CategoryEntity> all) {
        return all.stream().filter(current -> current.getParentCid() == parentId)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity.getCatId(), all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());
    }


}